<template>
  <div class="user-layout">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <h2>健康档案管理系统</h2>
          <span class="role">用户端</span>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" >
              </el-avatar>
              <span class="username">{{ username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="info" divided>个人信息</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main class="main-content">
        <div class="content-wrapper">
          <el-menu
            :default-active="activeMenu"
            class="user-menu"
            mode="horizontal"
            router
          >
            <el-menu-item index="/user/profile" >
              <el-icon><User /></el-icon>
              <span>基本信息</span>
            </el-menu-item>
            <el-menu-item index="/user/health">
              <el-icon><DataAnalysis /></el-icon>
              <span>体检数据</span>
            </el-menu-item>
            <el-menu-item index="/user/medication">
              <el-icon><MedicineBox /></el-icon>
              <span>用药记录</span>
            </el-menu-item>
          </el-menu>
          <div class="page-content">
            <router-view />
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
   <!-- 添加个人信息编辑对话框 -->
  <el-dialog
    v-model="showEditDialog"
    title="编辑个人信息"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="editFormRef"
      :model="editForm"
      :rules="editRules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" disabled />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realname">
        <el-input v-model="editForm.realname" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="editForm.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showEditDialog = false">取消</el-button>
      <el-button type="primary" @click="saveUserInfo" :loading="saving">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage,ElMessageBox } from 'element-plus'
import { ref, reactive} from 'vue'
import { getUserById, updataUser } from '@/api/userInfo/userInfo'
const showEditDialog = ref(false)
const editFormRef = ref()
const saving = ref(false)
const route = useRoute()
const router = useRouter()
// 获取存储的用户数据
const userString = localStorage.getItem('user')
// 转换为用户对象
interface UserInfo {
  id: string;
  username: string;
  realname: string | undefined;
  phone: string | undefined;
  email: string | undefined;
  elderlyId: string | undefined;
}
const user = ref<UserInfo | null>(null);
const editForm = reactive({
  id: '',
  username: '',
  realname: '',
  phone: '',
  email: ''
})

const editRules = {
  realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
}

onMounted(() => {
  console.log(userString)
  if (userString) {
    console.log('上面是String')
    try {
      user.value = JSON.parse(userString) as UserInfo;
    } catch (error) {
      console.error('解析用户数据失败:', error)
    }
    console.log(user) 
  }
  console.log('用户数据已加载')
})

const activeMenu = computed(() => route.path)

// 安全地获取用户名
const username = computed(() => {
  return user.value?.username ?? ''
})

const handleCommand = async (command: string) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      localStorage.removeItem('user')
      router.push('/login')
    } catch (error) {
      console.debug('退出操作取消:', error)
    }
  }

  if (command === 'info') {
    openEditDialog()
  }
}

const openEditDialog = () => {
  if (user.value) {
    editForm.id = user.value.id?.toString() ?? ''
    editForm.username = user.value.username
    editForm.realname = user.value.realname || ''
    editForm.phone = user.value.phone || ''
    editForm.email = user.value.email || ''
    showEditDialog.value = true
  }
}

const saveUserInfo = async () => {
    await editFormRef.value?.validate()
    saving.value = true
    try{
    const response = await updataUser(editForm)
    if (response.code === 200) {
      ElMessage.success('保存成功')
      const response = await getUserById(user.value?.id??'')
      user.value = response.data
      console.log(user.value)
      localStorage.setItem('user', JSON.stringify(user.value))
      showEditDialog.value = false
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }

}
    
</script>


<style scoped>
.user-layout {
  height: 100vh;
  width: 100vw;
  background: #f0f2f5;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left h2 {
  margin: 0;
  color: #333;
  font-size: 22px;
  font-weight: 600;
}

.role {
  margin-left: 16px;
  color: #409eff;
  font-size: 14px;
  background: #ecf5ff;
  padding: 4px 12px;
  border-radius: 12px;
  font-weight: 500;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.username {
  margin: 0 8px;
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.main-content {
  height: calc(100vh - 64px);
  padding: 0;
  background: #f0f2f5;
}

.content-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.user-menu {
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .header {
    padding: 0 20px;
  }
  
  .page-content {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .header {
    padding: 0 16px;
  }
  
  .header-left h2 {
    font-size: 18px;
  }
  
  .page-content {
    padding: 16px;
  }
  
  .user-menu {
    padding: 0 16px;
  }
}
</style> 